package com.itlong.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.esotericsoftware.minlog.Log;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.app.AppUserAccountBalanceDTO;
import com.itlong.cloud.POJO.DTO.common.LimitedDeviceDto;
import com.itlong.cloud.POJO.DTO.property.CheckQrCodeDTO;
import com.itlong.cloud.POJO.DTO.property.CloudIntercomChangeLogGetDTO;
import com.itlong.cloud.POJO.DTO.property.CloudIntercomDynamicPwdCheckDTO;
import com.itlong.cloud.POJO.DTO.property.CloudIntercomMediaGetDTO;
import com.itlong.cloud.POJO.PO.DeviceRunLogPO;
import com.itlong.cloud.POJO.PO.OperationSpecialLogPO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.common.CloudEntranceVO;
import com.itlong.cloud.POJO.VO.common.LimitedDeviceVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceWhiteListVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnLogIntercept;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.equip.commons.ICloudDeviceBaseServiceClient;
import com.itlong.cloud.equip.commons.ICloudElevatorServiceClient;
import com.itlong.cloud.equip.commons.ICloudEntranceServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceManageServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListServiceClient;
import com.itlong.cloud.equip.property.ICloudIntercomServiceClient;
import com.itlong.cloud.equip.property.IDeviceCloudControllerServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.iottp.IIotAliOSSServiceClient;
import com.itlong.cloud.paymenthub.IAccountBalanceServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.property.IPropertyUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.node.MapUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.IdWorker;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;

/**
 * <desc>
 * 云端智能设备接口控制器
 * </desc>
 *
 * @createDate 2017-11-15.
 */
@RestController
@RequestMapping("/smartCommunity/interface")
@RefreshScope
public class CloudBaseController {
    private static final Logger LOG = LoggerFactory.getLogger(CloudBaseController.class);

    @Value("${" + PlatformConstants.TCP_SERVER_IP + "}")
    public String TCP_SERVER_IP;
    @Value("${" + PlatformConstants.TCP_SERVER_PORT + "}")
    public String TCP_SERVER_PORT;
    @Value("${" + PlatformConstants.TCP_SERVER_HEARTBEAT + "}")
    public String TCP_SERVER_HEARTBEAT;

    @Value("${" + PlatformConstants.H5_PAYMENT_HTML + "}")
    public String H5_PAYMENT_HTML;

    @Value("${" + PlatformConstants.CLOUD_ELEVATOR_AESKEY + "}")
    private String cloudElevatorAeskey; //AES加密KEY

    @Value("${" + PlatformConstants.CLOUD_ELEVATOR_MD5KEY + "}")
    private String cloudElevatorMd5key;  //MD5加密KEY

    @Autowired
    ICloudIntercomServiceClient iCloudIntercomServiceClient;
    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;
    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;
    @Autowired
    ICloudElevatorServiceClient iCloudElevatorServiceClient;
    @Autowired
    IPropertyUserServiceClient iPropertyUserServiceClient;
    @Autowired
    IAccountBalanceServiceClient iAccountBalanceServiceClient;
    @Autowired
    RedisService redisService;
    @Autowired
    ICloudEntranceServiceClient iCloudEntranceServiceClient;
    @Autowired
    IDeviceCloudControllerServiceClient iDeviceCloudControllerServiceClient;

    @Autowired
    IOperateDeviceWhiteListServiceClient iOperateDeviceWhiteListServiceClient;

    @Autowired
    private IIotAliOSSServiceClient iIotAliOSSServiceClient;

    @Autowired
    private ICloudDeviceBaseServiceClient iCloudDeviceBaseService;


    @Autowired
    private IOperateDeviceManageServiceClient iOperateDeviceManageServiceClient;

    final IdWorker idWorker = new IdWorker(18);

//
//    final static IdWorker idWorker = new IdWorker(18);
//
//    @RequestMapping(value = "/getId", method = RequestMethod.POST)
//    public void getId(){
//        StringBuffer sb = new StringBuffer();
//        for (int i = 0; i < 500; i++) {
//            sb.append(idWorker.nextId() + ",");
//        }
//        LOG.info(sb.toString());
//    }

    /**
     * <desc>
     * 获取设备业务服务器地址
     * <desc/>
     *
     * @param sn         设备序列号
     * @param deviceType 设备类型，默认为空，表示云对讲（31/32）;云电梯(33)
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-15
     */
    @RequestMapping(value = "/device/getDeviceServer", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object getDeviceServer(String sn, String deviceType, HttpServletRequest request, String https) {
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            if(sn.length()<16){
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_ERROR.getErrorCode());
            }
            if(StringUtils.isBlank(StringHandlerUtil.getProjectIdBySn(sn))){
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            ProjectPO project = iOperateProjectServiceClient.getOneProject(StringHandlerUtil.getProjectIdBySn(sn));
            if (project == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PROJECT_NOT_EXIST.getErrorCode());
            }
            if (StringUtils.isNotBlank(https)) {
                project.setDeviceAddress(project.getDeviceAddress().replace("http://", "https://"));
            }

            //返回业务服务器地址
            Map<String, Object> map = new HashMap<>();
            map.put("businessServer", project.getDeviceAddress());
             //map.put("businessServer", "http://192.168.123.101:8083/cloudte");

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        } catch (Exception e) {
            throw new DataAccessException("【云设备】获取业务服务器地址失败", e);
        }
    }


    /**
     * <desc>
     * 设备登录认证
     * <desc/>
     *
     * @param sn
     * @param deviceType        设备类型，默认为空，表示云对讲（31/32）;云电梯(33)
     * @param doorCount         门禁控制器控门数量
     * @param deviceID
     * @param encryptionAbility 数据不存在则认为设备不支持加密传输。
     *                          0—设备不支持加密传输
     *                          1—设备支持自有加密方案
     *                          2—设备支持HTTPS安全传输
     *                          3—设备同时支持自有加密方案和HTTPS安全传输。
     * @param newDevice         标识是否是新云对讲
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-15
     */
    //@LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_DEVICE_LOGIN)
    @RequestMapping(value = "/device/login", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object login(String sn, String deviceType, Integer doorCount, String deviceID, Integer encryptionAbility, String newDevice, @RequestParam(value = "deviceUseEnvironment", required = false) String deviceUseEnvironment) {
        try {
            Date nowTime = new Date();
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            //判断项目状态
            Integer status = iOperateProjectServiceClient.getProjectStatus(StringHandlerUtil.getProjectIdBySn(sn));
            if (null == status) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PROJECT_NOT_EXIST.getErrorCode());
            } else if (NumberHandlerUtil.isEqual(status, DataStatusEnum.BAN.getType())) {
                //项目禁用时不允许设备登录
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PROJECT_IS_BANNED.getErrorCode());
            }
            if (StringUtils.isNotBlank(deviceType) && deviceType.equals("21")) {
                deviceType = StringHandlerUtil.strToIntDef(deviceType, 99, 16) + "";
            }
            LimitedDeviceDto getDTO = new LimitedDeviceDto();
            getDTO.setSn(sn);
            getDTO.setDeviceType(deviceType);
            getDTO.setEncryptionAbility(encryptionAbility + "");
            if (null != doorCount) {
                getDTO.setDoorCount(doorCount);
            }
            if("24".equals(deviceType)) {
                getDTO.setDeviceUseEnvironment(deviceUseEnvironment);
            }

            //保存受限设备和缓存设备最新更新时间
            LimitedDeviceVO limitedDeviceVO = iCloudDeviceBaseService.saveLimitedDevice(getDTO);
            if(limitedDeviceVO != null && limitedDeviceVO.getIsLimitedDevice()){
                Map<String, Object> result = new HashMap<>();
                result.put("token", limitedDeviceVO.getToken());
                result.put("invalidTime", limitedDeviceVO.getInvalidTime());
                result.put("encryptMethod", limitedDeviceVO.getEncryptMethod());
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_LIMITED_DEVICE_ERROR.getErrorCode(), result);
            }else {
                Integer devStatus;       //0删除 1正常 2禁用
                if (StringUtils.isNotBlank(deviceType) && !deviceType.equals("99") &&
                        deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {
                    //缓存设备最新时间
                    redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getElevatorDeviceUniqueBySn(sn), System.currentTimeMillis() + "");
                    //云电梯 判断设备状态
                    //判断项目是否开启云电梯
                    if (!iOperateProjectServiceClient.checkProjectCloudDeviceStatus(StringHandlerUtil.getProjectIdBySn(sn), 2)) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PROJECT_ELEVATOR_IS_BANNED.getErrorCode());
                    }
                    devStatus = iCloudElevatorServiceClient.getDeviceStatus(sn);
                    if (devStatus == null) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                    } else if (devStatus != DataStatusEnum.NORMAL.getType()) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                    }
                    CloudElevatorVO elevator = iCloudElevatorServiceClient.login(sn, encryptionAbility.toString());
                    Map<String, Object> result = new HashMap<>();
                    result.put("token", elevator.getToken());
                    result.put("invalidTime", elevator.getInvalidTime());
                    result.put("encryptMethod", elevator.getEncryptMethod());
                    if (elevator!=null){
                        OperationSpecialLogPO operationSpecialLogPO = new OperationSpecialLogPO();
                        operationSpecialLogPO.setLogId(LogicIdUtil.bussinessId());
                        operationSpecialLogPO.setRealName("系统");
                        operationSpecialLogPO.setAccount("系统");
                        operationSpecialLogPO.setOuterId(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
                        operationSpecialLogPO.setIp("");
                        operationSpecialLogPO.setOperateFunction("重启");
                        operationSpecialLogPO.setOperateWay("重启");
                        operationSpecialLogPO.setFunctionType(8);
                        operationSpecialLogPO.setOperateDec("系统重启设备成功！设备sn:"+sn+"。");
                        operationSpecialLogPO.setStatus(DataStatusEnum.NORMAL.getType());
                        operationSpecialLogPO.setCreateTime(nowTime);
                        operationSpecialLogPO.setUpdateTime(nowTime);
                        iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLogPO);

                    }

                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
                } else if ((StringUtils.isNotBlank(deviceType) && deviceType.equals("17")) ||
                        (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString())) ||
                        (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString()))||
                        (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString()))){
                    //缓存设备最新时间
                    redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getEntranceDeviceUniqueBySn(sn), System.currentTimeMillis() + "");
                    //云门禁登录 检测sn是否存在
                    String statusStr = iCloudEntranceServiceClient.checkSnExists(sn, doorCount, deviceType);
                    if (StringUtils.isEmpty(statusStr)) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                    }
                    if (!statusStr.contains("1")) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                    }
                    String deviceStatus = iCloudEntranceServiceClient.getStatusBySn(sn);
                    if (!"1".equals(deviceStatus)) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                    }
                    CloudEntranceVO entrance = iCloudEntranceServiceClient.login(sn, doorCount, encryptionAbility, deviceType);
                    if("24".equals(deviceType)) {
                        Thread.sleep(1000);
                    }
                    if (entrance != null) {
                        Map<String, Object> result = new HashMap<>();
                        result.put("token", entrance.getToken());
                        result.put("invalidTime", entrance.getInvalidTime());
                        result.put("encryptMethod", entrance.getEncryptMethod());

                        OperationSpecialLogPO operationSpecialLogPO = new OperationSpecialLogPO();
                        operationSpecialLogPO.setLogId(LogicIdUtil.bussinessId());
                        operationSpecialLogPO.setRealName("系统");
                        operationSpecialLogPO.setAccount("系统");
                        operationSpecialLogPO.setOuterId(StringHandlerUtil.getEntranceDeviceUniqueBySn(sn));
                        operationSpecialLogPO.setIp("");
                        operationSpecialLogPO.setOperateFunction("重启");
                        operationSpecialLogPO.setOperateWay("重启");
                        operationSpecialLogPO.setFunctionType(8);
                        operationSpecialLogPO.setOperateDec("系统重启设备成功！设备sn:"+sn+"。");
                        operationSpecialLogPO.setStatus(DataStatusEnum.NORMAL.getType());
                        operationSpecialLogPO.setCreateTime(nowTime);
                        operationSpecialLogPO.setUpdateTime(nowTime);
                        iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLogPO);

                        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
                    }
                    return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
                } else if (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_CLUSTER_CONTROLLER.getType().toString())) {
                    //群控器
                    //缓存设备最新时间
                    redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getControllerDeviceUniqueBySn(sn), System.currentTimeMillis() + "");
                    devStatus = iDeviceCloudControllerServiceClient.getDeviceStatus(sn);
                    if (devStatus == null) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                    } else if (devStatus != DataStatusEnum.NORMAL.getType()) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                    }
                    CloudControllerVO controller = iDeviceCloudControllerServiceClient.login(sn, encryptionAbility.toString());
                    Map<String, Object> result = new HashMap<>();
                    result.put("token", controller.getToken());
                    result.put("invalidTime", controller.getInvalidTime());
                    result.put("encryptMethod", controller.getEncryptMethod());
                    if (controller!=null){
                        OperationSpecialLogPO operationSpecialLogPO = new OperationSpecialLogPO();
                        operationSpecialLogPO.setLogId(LogicIdUtil.bussinessId());
                        operationSpecialLogPO.setRealName("系统");
                        operationSpecialLogPO.setAccount("系统");
                        operationSpecialLogPO.setOuterId(StringHandlerUtil.getControllerDeviceUniqueBySn(sn));
                        operationSpecialLogPO.setIp("");
                        operationSpecialLogPO.setOperateFunction("重启");
                        operationSpecialLogPO.setOperateWay("重启");
                        operationSpecialLogPO.setFunctionType(8);
                        operationSpecialLogPO.setOperateDec("系统重启设备成功！设备sn:"+sn+"。");
                        operationSpecialLogPO.setStatus(DataStatusEnum.NORMAL.getType());
                        operationSpecialLogPO.setCreateTime(nowTime);
                        operationSpecialLogPO.setUpdateTime(nowTime);
                        iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLogPO);
                    }
                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
                } else {
                    //云对讲 判断设备状态
                    //缓存设备最新时间
                    redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + (StringHandlerUtil.getProjectIdBySn(sn) + "3" + StringHandlerUtil.getDeviceIdBySnForCloudIntercom(sn)), System.currentTimeMillis() + "");

                    //判断项目是否开启云对讲
                    if (!iOperateProjectServiceClient.checkProjectCloudDeviceStatus(StringHandlerUtil.getProjectIdBySn(sn), 1)) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PROJECT_INTERCOM_IS_BANNED.getErrorCode());
                    }
                    devStatus = iCloudIntercomServiceClient.getDeviceState(sn);
                    if (devStatus == null) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                    } else if (devStatus != DataStatusEnum.NORMAL.getType()) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                    }
                    CloudIntercomDeviceVO result = iCloudIntercomServiceClient.cloudIntercomLogin(sn, newDevice);
                    if (result != null) {
                        result.setTcpIp(TCP_SERVER_IP);
                        result.setTcpPort(TCP_SERVER_PORT);
                        //result.setClientServer("119.23.234.68");
                        result.setClientServer("118.31.11.122");
                        result.setHeartbeat(TCP_SERVER_HEARTBEAT);
                        result.setH5PaymentHtml(H5_PAYMENT_HTML);


                        OperationSpecialLogPO operationSpecialLogPO = new OperationSpecialLogPO();
                        operationSpecialLogPO.setLogId(LogicIdUtil.bussinessId());
                        operationSpecialLogPO.setRealName("系统");
                        operationSpecialLogPO.setAccount("系统");
                        operationSpecialLogPO.setOuterId(StringHandlerUtil.getDeviceUniqueBySn(sn));
                        operationSpecialLogPO.setIp("");
                        operationSpecialLogPO.setOperateFunction("重启");
                        operationSpecialLogPO.setOperateWay("重启");
                        operationSpecialLogPO.setFunctionType(8);
                        operationSpecialLogPO.setOperateDec("系统重启设备成功！设备sn:"+sn+"。");
                        operationSpecialLogPO.setStatus(DataStatusEnum.NORMAL.getType());
                        operationSpecialLogPO.setCreateTime(nowTime);
                        operationSpecialLogPO.setUpdateTime(nowTime);
                        iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLogPO);
                    }

                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
                }
            }


        } catch (Exception e) {
            throw new DataAccessException("【云设备】设备云端登录认证失败", e);
        }
    }


    /**
     * <desc>
     * 设备主动获取基本信息
     * </desc>
     *
     * @param token
     * @param sn         设备sn
     * @param deviceType 设备类型 设备类型，默认为空，表示云对讲（31/32）;云电梯(33)
     * @return
     * @author Jiaqi.X
     * @createDate 2018-03-22
     */
    @RequestMapping(path = "/device/pullDeviceInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullDeviceInfo(String token, String sn, Integer doorCount, String deviceType, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params == null) {
                    new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                token = params.get("token").toString();
                deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() :
                        params.get("deviceType") != null ? params.get("deviceType").toString() : "99";
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                if(deviceType.equals("17") || deviceType.equals("22") || deviceType.equals("24")|| deviceType.equals("18")){
                    doorCount = (Integer) params.get("doorCount");
                }
            }
            if (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {
                //云电梯
                CloudElevatorVO elevatorVO = iCloudElevatorServiceClient.retrieve(token);
                if (StringUtils.isBlank(elevatorVO.getIotDeviceId())) {
                    //如果缓存中的iotDeviceId说明设备是第一次进行云端登录并获取基本信息，需从数据库当中读出异步iot信息，并更新缓存
                    elevatorVO = iCloudElevatorServiceClient.updateCloudElevatorIotCacheInfo(elevatorVO);
                    //如果获取的信息还是没有阿里云信息说明注册失败，返回设备需要重新进行登录信息
                    if (StringUtils.isBlank(elevatorVO.getIotDeviceId())) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_IOT_REGISTER_ERROR.getErrorCode());
                    }
                }
                //查询云电梯所绑定的摄像头相关参数配置
                DeviceAiCameraInfoVO aiCameraInfoVO = iCloudElevatorServiceClient.getAiCameraInfoByElevatorDeviceUnique(elevatorVO);
                Map<String, Object> result = new HashMap<>();
                result.put("projectName", elevatorVO.getProjectName());
                result.put("deviceName", elevatorVO.getDeviceName());
                result.put("rootPwd", elevatorVO.getRootPwd());
                result.put("rootPort", elevatorVO.getRootPort());
                result.put("propertyValueOpen", elevatorVO.getPropertyValueOpen());
                Map<String, Object> iotData = new HashMap<>();
                iotData.put("iotProductKey", elevatorVO.getIotProductKey());
                iotData.put("iotDeviceName", elevatorVO.getDeviceUnique());
                iotData.put("iotDeviceSecret", elevatorVO.getIotDeviceSecret());
                iotData.put("iotVersion", elevatorVO.getIotVersion()==null?"0":elevatorVO.getIotVersion().toString());
                iotData.put("iotPlatform", elevatorVO.getIotPlatform());
                iotData.put("iotDevicePassword", elevatorVO.getIotDevicePassword());
                iotData.put("iotDeviceId", elevatorVO.getIotDeviceId());
                if(aiCameraInfoVO!=null){
                    AiCameraInfoVO cameraInfoVO = new AiCameraInfoVO();
                    cameraInfoVO.setDeviceIp(aiCameraInfoVO.getCameraIp());
                    cameraInfoVO.setIsOpenAlarm(aiCameraInfoVO.getAlarmStatus());
                    cameraInfoVO.setIsUploadPicture(aiCameraInfoVO.getUploadStatus());
                    result.put("webCam",cameraInfoVO);
                }
                result.put("iotData", iotData);
                result.put("deploys", elevatorVO.getDeploys());
                result.put("operationMode", elevatorVO.getChargeMode());
                result.put("equipMode", elevatorVO.getEquipMode());
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
            } else if (StringUtils.isNotBlank(deviceType) &&
                    (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString()) ||
                            deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString()) ||
                            deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())||
                            deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString()))){
                CloudEntranceVO entranceVO = iCloudEntranceServiceClient.retrieve(token);
                entranceVO.setDoorCount(doorCount);
                if (StringUtils.isBlank(entranceVO.getIotDeviceId()) || entranceVO.getIotVersion() == null) {
                    //如果缓存中的iotDeviceId说明设备是第一次进行云端登录并获取基本信息，需从数据库当中读出异步iot信息，并更新缓存
                    entranceVO = iCloudEntranceServiceClient.updateCloudEntranceIotCacheInfo(entranceVO);
                    //如果获取的信息还是没有阿里云信息说明注册失败，返回设备需要重新进行登录信息
                    if (StringUtils.isBlank(entranceVO.getIotDeviceId())) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_IOT_REGISTER_ERROR.getErrorCode());
                    }
                }
                //根据sn查询该设备信息
                CloudTalkFaceApplyInfoVO vo = iCloudEntranceServiceClient.getDoorFaceInfo(sn);
                Map<String, Object> deviceMap = iCloudEntranceServiceClient.getDeviceInfoBySn(sn, doorCount);
                Map<String, Object> result = new HashMap<>();
                result.put("face", vo);
                result.put("projectName", deviceMap.get("projectName"));
                result.put("deviceName", deviceMap.get("deviceName"));
                result.put("rootPwd", deviceMap.get("rootPwd"));
                result.put("rootPort", deviceMap.get("rootPort"));
                result.put("propertyValueOpen", entranceVO.getPropertyValueOpen());
                Map<String, Object> iotData = new HashMap<>();
                iotData.put("iotProductKey", deviceMap.get("iotProductKey"));
                iotData.put("iotDeviceName", entranceVO.getMainDeviceUnique());
                iotData.put("iotDeviceSecret", entranceVO.getIotDeviceSecret());
                iotData.put("iotDeviceId", deviceMap.get("iotDeviceId"));
                iotData.put("iotPlatform", deviceMap.get("iotPlatform"));
                iotData.put("iotDevicePassword", deviceMap.get("iotDevicePassword"));
                if (entranceVO.getIotVersion() == null || entranceVO.getIotVersion().toString().equals("0")) {
                    iotData.put("iotVersion", "0");
                } else {
                    iotData.put("iotVersion", "1");
                }
                result.put("iotData", iotData);
                result.put("doorStatus", deviceMap.get("doorStatus"));
                result.put("deploys", entranceVO.getDeploys());
                result.put("elevatorDeploys", entranceVO.getElevatorDeploys());
//                result.put("chargeMode", entranceVO.getChargeMode());
//                result.put("equipMode", entranceVO.getEquipMode());
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
            } else if (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_CLUSTER_CONTROLLER.getType().toString())) {
                //群控器
                CloudControllerVO cluster = iDeviceCloudControllerServiceClient.retrieve(token);
                if (StringUtils.isBlank(cluster.getIotDeviceId())) {
                    //如果缓存中的iotDeviceId说明设备是第一次进行云端登录并获取基本信息，需从数据库当中读出异步iot信息，并更新缓存
                    cluster = iDeviceCloudControllerServiceClient.updateCloudClusterIotCacheInfo(cluster);
                    //如果获取的信息还是没有阿里云信息说明注册失败，返回设备需要重新进行登录信息
                    if (StringUtils.isBlank(cluster.getIotDeviceId())) {
                        return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_IOT_REGISTER_ERROR.getErrorCode());
                    }
                }
                Map<String, Object> result = new HashMap<>();
                result.put("projectName", cluster.getProjectName());
                result.put("deviceName", cluster.getDeviceName());
                result.put("rootPwd", cluster.getRootPwd());
                result.put("rootPort", cluster.getRootPort());
                result.put("bindList", cluster.getBindList());
                Map<String, Object> iotData = new HashMap<>();
                iotData.put("iotProductKey", cluster.getIotProductKey());
                iotData.put("iotDeviceName", cluster.getDeviceUnique());
                iotData.put("iotDeviceSecret", cluster.getIotDeviceSecret());
                iotData.put("iotVersion", cluster.getIotVersion());
                iotData.put("iotPlatform", cluster.getIotPlatform());
                iotData.put("iotDevicePassword", cluster.getIotDevicePassword());
                iotData.put("iotDeviceId", cluster.getIotDeviceId());
                result.put("iotData", iotData);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
            } else {
                //云对讲
                CloudTalkFaceApplyInfoVO vo = iCloudIntercomServiceClient.pullDeviceInfo(sn);
                CloudTalkIotInfoVO cloudTalkFaceApplyInfoVO = iCloudIntercomServiceClient.getCloudTalkIotInfo(sn);
                String endTime = iCloudIntercomServiceClient.getEndTimeBySn(sn);
                Map<String, Object> result = new HashMap<>();
                result.put("endTime", StringUtils.isEmpty(endTime) ? "" : endTime);
                result.put("face", vo);
                Map<String, Object> iotData = new HashMap<>();
                iotData.put("iotProductKey", cloudTalkFaceApplyInfoVO.getIotProductKey());
                iotData.put("iotDeviceName", cloudTalkFaceApplyInfoVO.getDeviceUnique());
                iotData.put("iotDeviceSecret", cloudTalkFaceApplyInfoVO.getIotDeviceSecret());
                iotData.put("iotVersion", cloudTalkFaceApplyInfoVO.getIotVersion());
                result.put("iotData", iotData);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
            }
        } catch (Exception e) {
            throw new DataAccessException("【云设备】主动获取基本信息失败", e);
        }
    }

    /**
     * <desc>
     * 云端接收设备端的通行记录
     * </desc>
     *
     * @param sn
     * @param type             记录类型 4表示电话呼叫，7表示设备上密码通行
     * @param deviceRecordJson json映射信息
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/21
     */
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_DEVICE_RECORD)
    @RequestMapping(path = "/device/pushDeviceRecord", method = {RequestMethod.POST, RequestMethod.GET})
    public Object pushDeviceRecord(String deviceType, String token, String sn, Integer type, String deviceRecordJson, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(token)) {
            Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
            if (params == null) {
                new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            token = params.get("token").toString();
            sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
            deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                    ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() :
                    params.get("deviceType") != null ? params.get("deviceType").toString() : "99";
            if (StringUtils.isNotBlank(deviceType) && Integer.valueOf(deviceType) == PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType()) {
                deviceRecordJson = StringHandlerUtil.getNullOrStringForObject(params.get("deviceRecordArr"));
                List<Map<String, Object>> jsons = JsonUtil.decode(deviceRecordJson, new TypeReference<List<Map<String, Object>>>() {
                });
                type = Integer.valueOf(jsons.get(0).get("type").toString());
            }
        }
        //检查是否是二维码计次通行记录
        try {
            boolean isQrCode = false;
            List<Map<String, Object>> qrcodes;
            List<Map<String, Object>> qrcodeList = new ArrayList<>();
            List<Map<String, Object>> others = new ArrayList<>();
            if (StringUtils.isNotBlank(deviceType) && Integer.valueOf(deviceType) == PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType()) {
                qrcodes = JsonUtil.decode(deviceRecordJson, new TypeReference<List<Map<String, Object>>>() {
                });
                for (Map<String, Object> map : qrcodes) {
                    Integer passType = Integer.valueOf(map.get("type").toString());
                    if ((passType == 8 || passType == 11 || passType == 17)
                            && map.get("mac") != null) {
                        isQrCode = true;
                        qrcodeList.add(map);
                    } else {
                        others.add(map);
                        type = passType;
                    }
                }
            } else {
                if (StringUtils.isNotBlank(deviceRecordJson)) {
                    qrcodes = JsonUtil.decode(deviceRecordJson, new TypeReference<List<Map<String, Object>>>() {
                    });
                } else {
                    Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                    qrcodes = JsonUtil.decode(JsonUtil.toJSON(params.get("deviceRecordJson")), new TypeReference<List<Map<String, Object>>>() {
                    });
                }
                for (Map<String, Object> map : qrcodes) {
                    Integer passType = Integer.valueOf(map.get("type").toString());
                    if ((passType == 8 || passType == 11 || passType == 17)
                            && map.get("mac") != null) {
                        isQrCode = true;
                        qrcodeList.add(map);
                    } else {
                        others.add(map);
                        type = passType;
                    }
                }
            }
            if (isQrCode) {
                String jsonRecord = JsonUtil.toJSON(qrcodeList);
                iPropertyEquipServiceClient.uploadQrcodePssRecord(jsonRecord, StringUtils.isNotBlank(deviceType) ? Integer.valueOf(deviceType) : null, sn);
                if (others == null || others.isEmpty()) {
                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
                } else {
                    deviceRecordJson = JsonUtil.toJSON(others);
                }
            }
        } catch (Exception e) {
//            LOG.info("【通行记录异常数据】"+deviceRecordJson);
        }
        if (StringUtils.isBlank(deviceType)) {
            deviceType = PropertyEquipTypeEnum.CLOUD_INTERCOM.getType().toString();
        }
        if (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString())
                || deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString())
                || deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())
                || deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString())) {
            Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
            //LOG.info("请求参数：" + params);
            List<HashMap> recordJson = (List<HashMap>) params.get("deviceRecordJson");
            deviceRecordJson = JSON.toJSONString(recordJson);
            try {
                //LOG.info("通行记录对象数组：" + deviceRecordJson);
                List<Map<String, Object>> parseJson = JsonUtil.decode(deviceRecordJson, new TypeReference<List<Map<String, Object>>>() {
                });
                type = Integer.valueOf(parseJson.get(0).get("type").toString());
            } catch (IOException e) {
                LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】解析通行开门通行记录json失败", e);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PHONE_PASS_RECORD_ERROR.getErrorCode());
            } catch (NumberFormatException e) {
                LOG.error("云门禁pushDeviceRecord【云端接收设备端的通行记录】解析通行开门通行记录json中type类型失败", e);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PHONE_PASS_RECORD_ERROR.getErrorCode());
            }
        }
        //合法性判断
        if (StringUtils.isBlank(sn)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
        }
        if (type == null) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_RECORD_TYPE_IS_NULL.getErrorCode());
        }
        if (StringUtils.isBlank(deviceRecordJson)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PASS_RECORD_IS_NULL.getErrorCode());
        }
//        LOG.info(String.format("【pushDeviceRecord请求参数】 sn:%s，type：%s，deviceRecordJson：%s",
//                sn, type, deviceRecordJson));
        if (!deviceType.equals(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString()) && !deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString())
                && !deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString())
                && !NumberHandlerUtil.isEqual(type,4) && !NumberHandlerUtil.isEqual(type,7) && !NumberHandlerUtil.isEqual(type,12)
                && !NumberHandlerUtil.isEqual(type,11) && !NumberHandlerUtil.isEqual(type,8) && !NumberHandlerUtil.isEqual(type,5)
                && !NumberHandlerUtil.isEqual(type,6) && !NumberHandlerUtil.isEqual(type,14) && !NumberHandlerUtil.isEqual(type,15)
                && !NumberHandlerUtil.isEqual(type,9) && !NumberHandlerUtil.isEqual(type,16) && !NumberHandlerUtil.isEqual(type,10)
                && !NumberHandlerUtil.isEqual(type,17) && !NumberHandlerUtil.isEqual(type,13)){
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PASS_RECORD_TYPE_INVALID.getErrorCode());
        }
        //由于有上传云门禁或云联动器IOT网络开门通行记录数量较多导致超时问题，故在此处改为异步处理
        final String finalSn = sn;
        final Integer finalType = type;
        final String finalDeviceRecordJson = deviceRecordJson;
        final String finalDeviceType = deviceType;
        new Thread(() -> {
            try{
                iCloudIntercomServiceClient.pushDeviceRecord(finalSn, finalType, finalDeviceRecordJson, finalDeviceType);
            } catch (Exception e) {
                e.printStackTrace();
                throw new DataAccessException("【设备服务】云端接收设备端的通行记录失败", e);
            }
        }).start();
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
    }

    /**
     * <desc>
     * 获取物业公共信息—文字公告
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    @RequestMapping(value = "/device/pullPropertyOfText", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullPropertyOfText(CloudIntercomMediaGetDTO getDTO) {
        try {
            //合法性判断
            if (null == getDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            getDTO.setMediaType(MediaTypeEnum.TEXT.getType().toString());
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomServiceClient.getDeviceMedias(getDTO);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("textMediaInfoArr", mediaVOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取文字公共信息失败", e);
        }
    }

    /**
     * <desc>
     * 获取物业公共信息—图片
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    @RequestMapping(value = "/device/pullPropertyOfPic", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullPropertyOfPic(CloudIntercomMediaGetDTO getDTO, HttpServletRequest request) {
        try {
            //合法性判断
            if (null == getDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(getDTO.getToken())) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params == null) {
                    new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                getDTO.setSn(params.get("sn") == null ? "" : params.get("sn").toString());
                getDTO.setPageSize(params.get("sn") == null ? 10 : (Integer) params.get("pageSize"));
                getDTO.setMediaType(params.get("sn") == null ? "" : params.get("sn").toString());
                getDTO.setDeviceType(params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() :
                        params.get("deviceType") != null ? params.get("deviceType").toString() : "99");
                getDTO.setToken(params.get("token") == null ? "" : params.get("token").toString());
            }
            if (getDTO.getDeviceType() != null && getDTO.getDeviceType().equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())) {
                getDTO.setDeviceUnique(iCloudEntranceServiceClient.retrieve(getDTO.getToken()).getMainDeviceUnique());
            }

            getDTO.setMediaType(MediaTypeEnum.IMGAE.getType().toString());
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomServiceClient.getDeviceMedias(getDTO);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("picMediaInfoArr", mediaVOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取图片公共信息失败", e);
        }
    }

    /**
     * <desc>
     * 获取物业公共信息—视频
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    @RequestMapping(value = "/device/pullPropertyOfVideo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullPropertyOfVideo(CloudIntercomMediaGetDTO getDTO) {
        try {
            //合法性判断
            if (null == getDTO) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            getDTO.setMediaType(MediaTypeEnum.VIDEO.getType().toString());
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomServiceClient.getDeviceMedias(getDTO);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("videoMediaInfoArr", mediaVOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取视频公共信息失败", e);
        }
    }

    /**
     * <desc>
     * 云设备获取待轮询命令(增量)
     * <desc/>
     *
     * @param getDTO 分页获取
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    @RequestMapping(value = "/device/pullChangeLog", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullChangeLog(CloudIntercomChangeLogGetDTO getDTO, HttpServletRequest request) {
        try {
            //获取设备传参，如普通dto类当中没有参数那么再使用解密的方式获取
            if (getDTO.getToken() == null) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params == null) {
                    new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                if (params != null) {
                    getDTO = (CloudIntercomChangeLogGetDTO) MapUtil.mapToObject(params, CloudIntercomChangeLogGetDTO.class);
                }
            }


            //合法性判断
            if (null == getDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(getDTO.getSn())) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            getDTO.setDeviceType(getDTO.getDeviceType() != null && getDTO.getDeviceType().equals("21") ?
                    ((Integer) StringHandlerUtil.strToIntDef(getDTO.getDeviceType(), 99, 16)).toString() :
                    getDTO.getDeviceType() != null ? getDTO.getDeviceType() : "99");
            //处理受限设备 非云对讲设备
            if(StringUtils.isNotBlank(getDTO.getDeviceType()) && !getDTO.getDeviceType().equals("31") && !getDTO.getDeviceType().equals("32")){
                handleLimitDevice(getDTO);
            }

            if (getDTO.getPage() == null) {
                getDTO.setPage(1);
            }
            if (getDTO.getPageSize() == null) {
                getDTO.setPageSize(20);
            }
            Page page = null;
            if (getDTO.getDeviceType().equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString()) || getDTO.getDeviceType().equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_CLUSTER_CONTROLLER.getType().toString())) {
                page = iCloudElevatorServiceClient.getChangeLogPage(getDTO);
            } else if (getDTO.getDeviceType().equals(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString()) ||
                    getDTO.getDeviceType().equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString()) ||
                    getDTO.getDeviceType().equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())||
                    getDTO.getDeviceType().equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString())){
                //检测sn是否存在 由于校验会出现如二门 两个门禁先后被禁用，后面被禁用的门禁指令设备获取不了，故此处取消校验
                //if(iCloudEntranceServiceClient.checkSnExists(getDTO.getSn(),getDTO.getDoorCount()) == 0){
                //    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_ENTRANCE_SN_ERROR.getErrorCode());
                //}
                page = iCloudEntranceServiceClient.getDeviceChangeLogOrders(getDTO);
            } else {
                if (!NumberHandlerUtil.isGreaterThan(iCloudIntercomServiceClient.checkSnExist(getDTO.getSn()), 0)) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                }
                page = iCloudIntercomServiceClient.getDeviceChangeLogOrders(getDTO);
            }
            if (getDTO.getPage() == null) {
                getDTO.setPage(1);
            }
            if (getDTO.getPageSize() == null) {
                getDTO.setPageSize(20);
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("total", page.getPage().getTotalNumber());
            resultMap.put("page", page.getPage().getCurrentPage());
            resultMap.put("currentTotal", page.getRows().size());
            resultMap.put("haveNext", page.getPage().getTotalPage() - page.getPage().getCurrentPage() > 0 ? 1 : 0);
            resultMap.put("commandArr", page.getRows());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取轮询命令失败", e);
        }
    }

    private void handleLimitDevice(CloudIntercomChangeLogGetDTO getDTO){
        if(null == getDTO.getDeviceType() || StringUtils.isBlank(getDTO.getDeviceType()) || "99".equals(getDTO.getDeviceType())){
            //缓存设备最新时间
//            redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getDeviceIdBySnForCloudIntercom(getDTO.getSn()), System.currentTimeMillis() + "");
            redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + (StringHandlerUtil.getProjectIdBySn(getDTO.getSn()) + "3" + StringHandlerUtil.getDeviceIdBySnForCloudIntercom(getDTO.getSn())), System.currentTimeMillis() + "");
            return;
        }
        Integer limitDeviceTotal = iCloudDeviceBaseService.getLimitDeviceTotalByDTO(getDTO);
        switch (PropertyEquipTypeEnum.getByEquipType(Integer.valueOf(getDTO.getDeviceType()))) {
            //电梯
            case CLOUD_ELEVATOR_DEVICE_TYPE:
                //缓存设备最新时间
                redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getElevatorDeviceUniqueBySn(getDTO.getSn()), System.currentTimeMillis() + "");

                if(limitDeviceTotal > 0) {
                    //在线状态保存 超时时间设置五分钟
                    redisService.set(RedisConstant.REDIS_IOT_LIMITED_CLOUD_ELEVATOR_STATE_CACHE + StringHandlerUtil.getElevatorDeviceUniqueBySn(getDTO.getSn()),
                            RedisConstant.REDIS_IOT_LIMITED_CLOUD_ELEVATOR_STATE_CACHE_TIME,"1");
                }
                break;
            //群控
            case CLOUD_ELEVATOR_CLUSTER_CONTROLLER:
                //缓存设备最新时间
                redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getControllerDeviceUniqueBySn(getDTO.getSn()), System.currentTimeMillis() + "");
                //在线状态保存 超时时间设置五分钟
                if(limitDeviceTotal > 0) {
                    redisService.set(RedisConstant.DEVICE_LIMITED_CLUSTER_IS_ONLINE_KEY + StringHandlerUtil.getControllerDeviceUniqueBySn(getDTO.getSn()),
                            RedisConstant.DEVICE_LIMITED_CLUSTER_IS_ONLINE_CACHE_TIME, "1");
                }
                break;
            case CLOUD_ENTRANCE:

                for (int i = 0; i < getDTO.getDoorCount(); i++){
                    StringBuffer sb = new StringBuffer((Integer.valueOf(StringHandlerUtil.getDeviceIdBySn(getDTO.getSn())) + i) + "");
                    for (int j = sb.length(); j < 4; j++){
                        sb.insert(0, "0");
                    }
                    //缓存设备最新时间
                    redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getProjectIdBySn(getDTO.getSn()) + "2" + sb.toString(), System.currentTimeMillis() + "");
                }
                CloudIntercomChangeLogGetDTO cloudIntercomChangeLogGetDTO = new CloudIntercomChangeLogGetDTO();
                cloudIntercomChangeLogGetDTO.setSn(getDTO.getSn());
                cloudIntercomChangeLogGetDTO.setDeviceType(getDTO.getDeviceType());
                cloudIntercomChangeLogGetDTO.setCloudDeviceType("22");
                limitDeviceTotal = iCloudDeviceBaseService.getLimitDeviceTotalByDTO(cloudIntercomChangeLogGetDTO);
                if(limitDeviceTotal > 0) {
                    //在线状态保存 超时时间设置五分钟
                    redisService.set(RedisConstant.DEVICE_LIMITED_ENTRANCE_IS_ONLINE_KEY + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()),
                            RedisConstant.DEVICE_LIMITED_ENTRANCE_IS_ONLINE_CACHE_TIME, "1");
                }
                break;
            case CLOUD_ENTRANCE_DEVICE:
            case CLOUD_WIPPEN_DEVICE:
                for (int i = 0; i < getDTO.getDoorCount(); i++){
                    StringBuffer sb = new StringBuffer((Integer.valueOf(StringHandlerUtil.getDeviceIdBySn(getDTO.getSn())) + i) + "");
                    for (int j = sb.length(); j < 4; j++){
                        sb.insert(0, "0");
                    }
                    //缓存设备最新时间
                    redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getProjectIdBySn(getDTO.getSn()) + "2" + sb.toString(), System.currentTimeMillis() + "");
                }
                CloudIntercomChangeLogGetDTO cloudIntercomChangeLogGet = new CloudIntercomChangeLogGetDTO();
                cloudIntercomChangeLogGet.setSn(getDTO.getSn());
                cloudIntercomChangeLogGet.setDeviceType(getDTO.getDeviceType());
                cloudIntercomChangeLogGet.setCloudDeviceType("23");
                limitDeviceTotal = iCloudDeviceBaseService.getLimitDeviceTotalByDTO(cloudIntercomChangeLogGet);
                if(limitDeviceTotal > 0) {
                    //在线状态保存 超时时间设置五分钟
                    redisService.set(RedisConstant.DEVICE_LIMITED_WIPPEN_IS_ONLINE_KEY + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()),
                            RedisConstant.DEVICE_LIMITED_WIPPEN_IS_ONLINE_CACHE_TIME, "1");
                }
                break;

            case HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE:
                //缓存设备最新时间
                redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()), System.currentTimeMillis() + "");
                //在线状态保存 超时时间设置五分钟
                if(limitDeviceTotal > 0) {
                    redisService.set(RedisConstant.DEVICE_LIMITED_ENTRANCE_IS_ONLINE_KEY + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()),
                            RedisConstant.DEVICE_LIMITED_UNIBODY_FACE_IS_ONLINE_CACHE_TIME, "1");
                }
                break;
            case CLOUD_UNIBODY_FACE_DEVICE:
                //缓存设备最新时间
                redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()), System.currentTimeMillis() + "");
                //在线状态保存 超时时间设置五分钟
                if(limitDeviceTotal > 0) {
                    redisService.set(RedisConstant.DEVICE_LIMITED_UNIBODY_FACE_IS_ONLINE_KEY + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()),
                            RedisConstant.DEVICE_LIMITED_UNIBODY_FACE_IS_ONLINE_CACHE_TIME, "1");
                }
                break;

            case PAD_FACE_RECOGNITION:
            case PAD:
                //缓存设备最新时间
                redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getProjectIdBySn(getDTO.getSn()) + "4" + StringHandlerUtil.getDeviceIdBySn(getDTO.getSn()), System.currentTimeMillis() + "");
                //在线状态保存 超时时间设置五分钟
                if(limitDeviceTotal > 0) {
                    redisService.set(RedisConstant.DEVICE_LIMITED_PAD_IS_ONLINE_KEY + StringHandlerUtil.getProjectIdBySn(getDTO.getSn()) + "4" + StringHandlerUtil.getDeviceIdBySn(getDTO.getSn()),
                            RedisConstant.DEVICE_LIMITED_PAD_IS_ONLINE_CACHE_TIME, "1");
                }
                break;
            default:
                break;
        }
    }

    /**
     * <desc>
     * 设备端轮询结果通知云端
     * <desc/>
     *
     * @param sn
     * @param id
     * @param deviceType 33云电梯 31/32云对讲
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    @RequestMapping(value = "/device/reportChangeLog", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object reportChangeLog(String token, String sn, String id, String deviceType, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params == null) {
                    new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                id = StringHandlerUtil.getNullOrStringForObject(params.get("id"));
                deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() :
                        params.get("deviceType") != null ? params.get("deviceType").toString() : "99";
            }
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(id)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_CHANGE_LOG_ORDER_ID_IS_NULL.getErrorCode());
            }
            if (StringUtils.isNotBlank(deviceType) && (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_CLUSTER_CONTROLLER.getType().toString()))) {
                //云电梯
                iCloudElevatorServiceClient.batchFinishChangeLogOrders(sn, id, deviceType);
            } else if (StringUtils.isNotBlank(deviceType) && (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString()))){
                //云门禁或云联动器
                iCloudEntranceServiceClient.batchFinishChangeLogOrders(sn, id);
            } else {
                //云对讲
                iCloudIntercomServiceClient.finishChangeLogOrders(sn, id);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】设备端轮询结果通知云端失败", e);
        }
    }

    /**
     * <desc>
     * 通知云端升级失败原因
     * <desc/>
     *
     * @param sn
     * @param id
     * @param deviceType 设备类型
     * @param msg        失败原因
     * @return
     * @author Qiang.S
     * @createDate 2019-06-25
     */
    @RequestMapping(value = "/device/reportUpdateResult", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object reportUpdateResult(String token, String sn, String id, String deviceType, String msg, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params == null) {
                    new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                id = StringHandlerUtil.getNullOrStringForObject(params.get("id"));
                msg = StringHandlerUtil.getNullOrStringForObject(params.get("msg"));
                deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() :
                        params.get("deviceType") != null ? params.get("deviceType").toString() : "99";
            }
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(id)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_CHANGE_LOG_ORDER_ID_IS_NULL.getErrorCode());
            }
            if (StringUtils.isNotBlank(deviceType) && (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_CLUSTER_CONTROLLER.getType().toString()))) {
                //云电梯
                iCloudElevatorServiceClient.reportUpdateResult(sn, id, msg);
            } else if (StringUtils.isNotBlank(deviceType) && (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString()))
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString())){
                //云门禁或云联动器
                iCloudEntranceServiceClient.reportUpdateResult(sn, id, msg);
            } else {
                //云对讲
                iCloudIntercomServiceClient.reportUpdateResult(sn, id, msg);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云设备】通知云端升级失败原因失败", e);
        }
    }

    /**
     * <desc>
     * 校验开门动态密码（校验成功后生成动态密码通行记录）
     * <desc/>
     *
     * @param checkDTO 动态密码信息
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-22
     */
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_CHECK_DYNAMIC_PWD)
    @RequestMapping(value = "/device/checkDynamicPwd", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object checkDynamicPwd(CloudIntercomDynamicPwdCheckDTO checkDTO, HttpServletRequest request) {
        String elapsedtime = "【checkDynamicPwd校验开门动态密码】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            //获取设备传参，如普通dto类当中没有参数那么再使用解密的方式获取
            if (checkDTO.getToken() == null) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params != null) {
                    checkDTO = (CloudIntercomDynamicPwdCheckDTO) MapUtil.mapToObject(params, CloudIntercomDynamicPwdCheckDTO.class);
                }
            }
            String deviceType = checkDTO.getDeviceType() != null && checkDTO.getDeviceType().equals("21") ?
                    ((Integer) StringHandlerUtil.strToIntDef(checkDTO.getDeviceType(), 99, 16)).toString() :
                    checkDTO.getDeviceType() != null ? checkDTO.getDeviceType() : "99";
            //合法性检测
            if (null == checkDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

//            LOG.info(String.format("【checkDynamicPwd校验开门动态密码-请求参数】 sn:%s，dynamicPwd：%s，roomNum：%s",
//                    checkDTO.getSn(), checkDTO.getDynamicPwd(), checkDTO.getRoomNum()));
            elapsedtime += ";checkDynamicPwd开始执行：" + DateUtil.fomatDate1(new Date());
            //校验动态密码
            Boolean result;
            if (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {
                //云电梯
                result = iCloudElevatorServiceClient.checkDynamicPwd(checkDTO);
            } else if (deviceType.equals(PropertyEquipTypeEnum.CLOUD_ENTRANCE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString())) {
                // 云门禁或云联动器
                result = iPropertyEquipServiceClient.checkDynamicPwd(checkDTO);
            } else {
                //云对讲
                result = iCloudIntercomServiceClient.checkDynamicPwd(checkDTO);
            }
//            LOG.info(String.format("【checkDynamicPwd校验开门动态密码-返回结果】 sn:%s，msg：%s",
//                    checkDTO.getSn(), result? BaseErrorCodeEnum.SUCCESS.getErrorCode().getCodeMsg():
//                            CloudDeviceErrorCodeEnum.CLOUD_DYNAMIC_PWD_INVALID.getErrorCode().getCodeMsg()));
            if (!result) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DYNAMIC_PWD_INVALID.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】校验开门动态密码失败", e);
        } finally {
            elapsedtime += ";【checkDynamicPwd校验开门动态密码】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }

    /**
     * <desc>
     * 校验身份信息
     * <desc/>
     *
     * @param sn
     * @param deviceType 设备类型，默认为空，表示云对讲（31/32）;云电梯(33)
     * @param deviceID
     * @param IDInfo     自定义数据对象
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-15
     */
    @RequestMapping(value = "/device/checkIDInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object checkIdentity(String token, String sn, String deviceType, String deviceID, String IDInfo, HttpServletRequest request) {
        try {
            Map<String, Object> cardInfo = new HashMap<>();
            if (StringUtils.isBlank(deviceType)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params == null) {
                    new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                token = params.get("token").toString();
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() :
                        params.get("deviceType") != null ? params.get("deviceType").toString() : "99";
                if (StringUtils.isNotBlank(deviceType) && Integer.valueOf(deviceType) == PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType()) {
                    cardInfo = JsonUtil.toObject(JsonUtil.toJSON(params.get("IDInfo")), HashMap.class);
                }
            } else {
                cardInfo = JsonUtil.toObject(IDInfo, HashMap.class);
            }
            //合法性判断
            if (StringUtils.isBlank(sn) || StringUtils.isBlank(StringHandlerUtil.getNullOrStringForObject(cardInfo.get("value")))) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            //判断项目状态
            Integer status = iOperateProjectServiceClient.getProjectStatus(StringHandlerUtil.getProjectIdBySn(sn));
            if (null == status) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PROJECT_NOT_EXIST.getErrorCode());
            } else if (NumberHandlerUtil.isEqual(status, DataStatusEnum.BAN.getType())) {
                //项目禁用时不允许设备登录
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PROJECT_IS_BANNED.getErrorCode());
            }
            // 云门禁身份证通行
            if (StringUtils.isNotBlank(deviceType) && ("17".equals(deviceType)
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())
                    || deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString())
            ) && cardInfo.get("tag") != null && "1".equals(cardInfo.get("tag").toString())) {
                // 校验身份证是否存在
                Map<String, Object> userInfo = iPropertyUserServiceClient.getUserInfoByIdCardKey(cardInfo.get("value").toString(), StringHandlerUtil.getProjectIdBySn(sn));
                if (userInfo == null || userInfo.isEmpty()) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_CARDID_NOT_EXISTS.getErrorCode());
                }
                // 添加云门禁用户身份证通行记录
                userInfo.put("sn", sn);
                iCloudEntranceServiceClient.saveIdCardPassRecord(userInfo);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
            if (StringUtils.isNotBlank(deviceType)) {
                //验证用户卡号
                String userId = iPropertyUserServiceClient.getUserIdByCardId(cardInfo.get("value").toString());
                if (StringUtils.isBlank(userId)) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_CARDID_NOT_EXISTS.getErrorCode());
                }
                AppUserAccountBalanceDTO appUserAccountBalanceDTO = new AppUserAccountBalanceDTO();
                appUserAccountBalanceDTO.setUserId(userId);
                appUserAccountBalanceDTO.setCardId(cardInfo.get("value").toString());
                appUserAccountBalanceDTO.setNum("0.01");
                appUserAccountBalanceDTO.setPayType(PayTypeEnum.ELEVATOR_CARD_PAY.getType());
                Map<String, Object> resultMap = iAccountBalanceServiceClient.updateBalance(appUserAccountBalanceDTO);
                if (resultMap.get("status").toString().equals("0")) {
                    //添加用户通行记录
                    String passId = iCloudElevatorServiceClient.saveCardPassRecord(token);
                    iAccountBalanceServiceClient.updateTradeSourceId(resultMap.get("recordId").toString(), passId);
                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
                } else {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_USER_BALANCE_LESS.getErrorCode());
                }
            } else {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【云电梯】校验身份信息失败", e);
        }
    }

    /**
     * <desc>
     * 设备更新
     * <desc/>
     *
     * @param sn
     * @param updateDeviceType 设备类型，表示云对讲（30linux/31安卓软件/32安卓硬件）;云电梯(33)  因此功能在V1.7版本屏蔽
     * @param packageType      4 维护程序，5 业务程序，6 桌面程序，7 通信程序
     * @return
     * @author Qiang.S
     * @createDate 2018-08-29
     */
    @RequestMapping(value = "/device/deviceUpdate", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object deviceUpdate(String sn, String updateDeviceType, String filePackage, String versionCode, String token, String packageType, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(sn)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params == null) {
                    new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                token = params.get("token").toString();
                filePackage = StringHandlerUtil.getNullOrStringForObject(params.get("filePackage"));
                versionCode = StringHandlerUtil.getNullOrStringForObject(params.get("versionCode"));
                packageType = StringHandlerUtil.getNullOrStringForObject(params.get("packageType"));
                updateDeviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() : params.get("deviceType").toString();
            }
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            Map<String, Object> resultMap = new HashMap<>();
            CloudDeviceUpdateInfoVO cloudDeviceUpdateInfoVO = new CloudDeviceUpdateInfoVO();
            if ("30".equals(updateDeviceType)) {//更新云对讲linux时
                cloudDeviceUpdateInfoVO = iCloudIntercomServiceClient.deviceIntercomUpdate(sn, "", versionCode, DeviceTypeEnum.DEVICE_CLOUD_LINUX_SCM.getType().toString());
            } else if ("31".equals(updateDeviceType)) {//更新云对讲软件时
                cloudDeviceUpdateInfoVO = iCloudIntercomServiceClient.deviceIntercomUpdate(sn, "", versionCode, DeviceTypeEnum.DEVICE_CLOUD_ANDROID_APK.getType().toString());
            } else if ("32".equals(updateDeviceType)) {//更新云对讲硬件时 无包名
                cloudDeviceUpdateInfoVO = iCloudIntercomServiceClient.deviceIntercomUpdate(sn, "", versionCode, DeviceTypeEnum.DEVICE_CLOUD_ANDROID_FIRMWARE.getType().toString());
            } else if ("33".equals(updateDeviceType) || "21".equals(updateDeviceType)) {//更新云电梯
                cloudDeviceUpdateInfoVO = iCloudElevatorServiceClient.deviceElevatorUpdate(sn, "", versionCode, DeviceTypeEnum.DEVICE_CLOUD_LINUX_SCM.getType().toString());
            }else if ("17".equals(updateDeviceType) || "22".equals(updateDeviceType)|| "18".equals(updateDeviceType)) {//更新云门禁或联动器时
                //CloudEntranceVO vo = iCloudEntranceServiceClient.retrieve(token);
                cloudDeviceUpdateInfoVO = iCloudEntranceServiceClient.deviceEntranceUpdate(sn,
                        ("17".equals(updateDeviceType) || "18".equals(updateDeviceType) ) ? "2" : "4");
            } else if ("128".equals(updateDeviceType)) {//群控器时
                cloudDeviceUpdateInfoVO = iCloudElevatorServiceClient.deviceClusterUpdate(sn, "", versionCode, DeviceTypeEnum.DEVICE_CLOUD_LINUX_SCM.getType().toString());
            } else if ("24".equals(updateDeviceType)) {//一体式人脸识别门禁
               // CloudEntranceVO vo = iCloudEntranceServiceClient.retrieve(token);
                cloudDeviceUpdateInfoVO = iCloudEntranceServiceClient.deviceUnibodyFaceUpdate(sn, packageType);
                CloudIntercomChangeLogGetDTO getDTO=new CloudIntercomChangeLogGetDTO();
                getDTO.setSn(sn);
                getDTO.setDeviceType("24");
                getDTO.setCloudDeviceType("24");
                Integer limitDeviceTotal = iCloudDeviceBaseService.getLimitDeviceTotalByDTO(getDTO);
                //缓存设备最新时间
                redisService.set(RedisConstant.DEVICE_NEW_UPDATE_CACHE_TIME + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()), System.currentTimeMillis() + "");
                //在线状态保存 超时时间设置五分钟
                if(limitDeviceTotal > 0) {
                    redisService.set(RedisConstant.DEVICE_LIMITED_UNIBODY_FACE_IS_ONLINE_KEY + StringHandlerUtil.getEntranceDeviceUniqueBySn(getDTO.getSn()),
                            RedisConstant.DEVICE_LIMITED_UNIBODY_FACE_IS_ONLINE_CACHE_TIME, "1");
                }

            }
            if (cloudDeviceUpdateInfoVO == null) {//无升级指令
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), null);
            }
            resultMap.put("fileName", cloudDeviceUpdateInfoVO.getFileName());
            resultMap.put("url", cloudDeviceUpdateInfoVO.getUrl());
            resultMap.put("md5", cloudDeviceUpdateInfoVO.getMd5());
            resultMap.put("versionCode", cloudDeviceUpdateInfoVO.getVersionCode());
            resultMap.put("id", cloudDeviceUpdateInfoVO.getCommandId());
            resultMap.put("filePackage", cloudDeviceUpdateInfoVO.getFilePackage());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【设备更新】设备更新失败", e);
        }
    }

    /**
     * <desc>
     * 云设备获取楼层映射信息
     * <desc/>
     *
     * @param sn
     * @param deviceType 33云电梯 31/32云对讲
     * @return
     * @author Jiaqi.X
     * @createDate 2018/11/22
     */
    @RequestMapping(value = "/device/pullFloorMapTable", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullFloorMapTable(String token, String sn, String deviceID, String deviceType, HttpServletRequest request) {
        LOG.info("【pullFloorMapTable start】{} {} {} {}", token, sn, deviceID, deviceType);
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                deviceID = StringHandlerUtil.getNullOrStringForObject(params.get("deviceID"));
                deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() : params.get("deviceType").toString();
            }
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iCloudElevatorServiceClient.getCloudDeviceFloorInfo(sn, deviceType));
        } catch (Exception e) {
            LOG.error("【pullFloorMapTable catch 获取楼层映射表失败】{} {} {} {}", token, sn, deviceID, deviceType);
            throw new DataAccessException("【云设备】获取楼层映射表失败", e);
        }
    }

    /**
     * <desc>
     * 获取黑名单信息
     * <desc/>
     *
     * @param sn
     * @param deviceType 33云电梯 31/32云对讲
     * @return
     * @author Jiaqi.X
     * @createDate 2019/09/09
     */
    @RequestMapping(value = "/device/pullBlackList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullBlackList(String token, String sn, String doorCount, String deviceID, String deviceType, String doorNum, String page, String pageSize, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                deviceID = StringHandlerUtil.getNullOrStringForObject(params.get("deviceID"));
                deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() : params.get("deviceType").toString();
                doorNum = StringHandlerUtil.getNullOrStringForObject(params.get("doorNum"));
                page = StringHandlerUtil.getNullOrStringForObject(params.get("page"));
                pageSize = StringHandlerUtil.getNullOrStringForObject(params.get("pageSize"));
                token = StringHandlerUtil.getNullOrStringForObject(params.get("token"));
                doorCount = StringHandlerUtil.getNullOrStringForObject(params.get("doorCount"));
            }
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isNotBlank(deviceType) && !deviceType.equals("99") &&
                    deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {
                //云电梯 判断设备状态
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iCloudElevatorServiceClient.pullBlackList(sn, page, pageSize));
            } else if ((StringUtils.isNotBlank(deviceType) && deviceType.equals("17")) ||
                    (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString()))
                    || (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString()))
                    || (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString()))){
                //云门禁登录 检测sn是否存在
                CloudEntranceVO entrance = iCloudEntranceServiceClient.retrieve(token);
                //云门禁登录 检测sn是否存在
                String statusStr = iCloudEntranceServiceClient.checkSnExists(sn, Integer.valueOf(doorCount), deviceType);
                if (StringUtils.isEmpty(statusStr)) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                }
                if (!statusStr.contains("1")) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                }
                entrance.setPage(page);
                entrance.setPageSize(pageSize);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iCloudEntranceServiceClient.pullBlackList(entrance));
            } else {
                //云对讲 判断设备状态
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iCloudIntercomServiceClient.pullBlackList(sn, page, pageSize));
            }
        } catch (Exception e) {
            throw new DataAccessException("【云设备】获取黑名单信息失败", e);
        }
    }


    /**
     * <desc>
     * 获取用户设备临时权限
     * <desc/>
     *
     * @param sn
     * @param deviceType 33云电梯 31/32云对讲
     * @return
     * @author Jiaqi.X
     * @createDate 2019/09/09
     */
    @RequestMapping(value = "/device/pullAuthTempInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullAuthTempInfo(String token, String sn, String doorCount, String deviceID, String deviceType, String doorNum, String page, String pageSize, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                sn = StringHandlerUtil.getNullOrStringForObject(params.get("sn"));
                deviceID = StringHandlerUtil.getNullOrStringForObject(params.get("deviceID"));
                deviceType = params.get("deviceType") != null && params.get("deviceType").toString().equals("21") ?
                        ((Integer) StringHandlerUtil.strToIntDef(params.get("deviceType").toString(), 99, 16)).toString() : params.get("deviceType").toString();
                doorNum = StringHandlerUtil.getNullOrStringForObject(params.get("doorNum"));
                page = StringHandlerUtil.getNullOrStringForObject(params.get("page"));
                pageSize = StringHandlerUtil.getNullOrStringForObject(params.get("pageSize"));
                token = StringHandlerUtil.getNullOrStringForObject(params.get("token"));
                doorCount = StringHandlerUtil.getNullOrStringForObject(params.get("doorCount"));
            }
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if(StringUtils.isNotEmpty(pageSize)){
                //本接口底层消耗时间比较多，外部最多提供50条数据
                pageSize  = "50";
            }
            if (StringUtils.isNotBlank(deviceType) && !deviceType.equals("99") &&
                    deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {
                //云电梯 判断设备状态
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iCloudElevatorServiceClient.getTempAuths(sn, page, pageSize));
            } else if ((StringUtils.isNotBlank(deviceType) && deviceType.equals("17")) ||
                    (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString())) ||
                    (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString()))||
                    (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString()))){
                //云门禁登录 检测sn是否存在
                CloudEntranceVO entrance = iCloudEntranceServiceClient.retrieve(token);
                //云门禁登录 检测sn是否存在
                String statusStr = iCloudEntranceServiceClient.checkSnExists(sn, Integer.valueOf(doorCount), deviceType);
                if (StringUtils.isEmpty(statusStr)) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                }
                if (!statusStr.contains("1")) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                }
                entrance.setPage(page);
                entrance.setPageSize(pageSize);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iCloudEntranceServiceClient.getTempAuths(entrance));
            } else {
                //云对讲 判断设备状态
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iCloudIntercomServiceClient.getTempAuths(sn, page, pageSize));
            }
        } catch (Exception e) {
            throw new DataAccessException("【云设备】获取临时权限信息失败", e);
        }
    }

    /**
     * <desc>
     * 校验访客二维码
     * <desc/>
     *
     * @param checkQrCodeDTO
     * @return
     * @author Jiaqi.X
     * @createDate 2019/09/09
     */
    @RequestMapping(value = "/device/checkQrCode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object checkVisitorQrCode(CheckQrCodeDTO checkQrCodeDTO, HttpServletRequest request) {
        try {
            //获取设备传参，如普通dto类当中没有参数那么再使用解密的方式获取
            if (checkQrCodeDTO.getToken() == null) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                if (params != null) {
                    checkQrCodeDTO = JsonUtil.toObject(JsonUtil.toJSON(params), CheckQrCodeDTO.class);
                }
            }
            String deviceType = checkQrCodeDTO.getDeviceType() != null && checkQrCodeDTO.getDeviceType().equals("21") ?
                    ((Integer) StringHandlerUtil.strToIntDef(checkQrCodeDTO.getDeviceType(), 99, 16)).toString() : checkQrCodeDTO.getDeviceType();
            //合法性判断
            if (StringUtils.isBlank(checkQrCodeDTO.getSn())) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            String deviceUnique = null;
            if (StringUtils.isNotBlank(deviceType) && !deviceType.equals("99") &&
                    deviceType.equals(PropertyEquipTypeEnum.CLOUD_ELEVATOR_DEVICE_TYPE.getType().toString())) {
                deviceUnique = StringHandlerUtil.getElevatorDeviceUniqueBySn(checkQrCodeDTO.getSn());
            } else if ((StringUtils.isNotBlank(deviceType) && deviceType.equals("17")) ||
                    (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE_TYPE.getType().toString()))
                    || (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString()))
                    || (StringUtils.isNotBlank(deviceType)&&deviceType.equals(PropertyEquipTypeEnum.HARDWARE_CLOUD_UNIBODY_ENTRANCE_DEVICE.getType().toString()))){
                //云门禁登录 检测sn是否存在
                CloudEntranceVO entrance = iCloudEntranceServiceClient.retrieve(checkQrCodeDTO.getToken());
                //云门禁登录 检测sn是否存在
                String statusStr = iCloudEntranceServiceClient.checkSnExists(checkQrCodeDTO.getSn(), Integer.valueOf(checkQrCodeDTO.getDoorCount()), deviceType);
                if (StringUtils.isEmpty(statusStr)) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
                }
                if (!statusStr.contains("1")) {
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
                }
                deviceUnique = StringHandlerUtil.getProjectIdBySn(checkQrCodeDTO.getSn()) + "2" + StringHandlerUtil.autlSupply(4, checkQrCodeDTO.getDoorNum(), "0");
            } else {
                deviceUnique = StringHandlerUtil.getDeviceUniqueBySn(checkQrCodeDTO.getSn());
            }
            checkQrCodeDTO.setDeviceUnique(deviceUnique);
            Boolean isOpen = iPropertyEquipServiceClient.checkVisitorQrcode(checkQrCodeDTO);
            if (isOpen) {
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            } else {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【云设备】校验二维码失败", e);

        }
    }

    /**
     * <desc>
     * 设备地址验证
     * </desc>
     *
     * @param encrypScript
     * @return
     * @Author Zhu.yj
     * @createDate 2019/12/13
     */

    @RequestMapping(path = "/device/checkDeviceMac", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @UnAuthAccessRequired
    public Object checkDeviceMac(String encrypScript, Integer encryptionAbility) {
        MessageVO messageVO = null;
        try {
            if (StringUtils.isBlank(encrypScript)) {
                return this.encryptResult(new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_NULL.getErrorCode()), encryptionAbility);
            }
            //解密
            String content = StringHandlerUtil.replaceBlank(encrypScript.substring(0, encrypScript.length() - 32));
            encrypScript = URLDecoder.decode(DesEncryptUtil.aesDecrypt(content, cloudElevatorAeskey), "UTF-8");
            JSONObject json = JSONObject.parseObject(encrypScript);
            if (json.get("mac") == null) {
                return this.encryptResult(new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_NULL.getErrorCode()), encryptionAbility);
            }

            //获取设备白名单信息结果 status,useStatus
            OperateDeviceWhiteListVO operateDeviceWhiteListVO = iOperateDeviceWhiteListServiceClient.getWhiteListByMac(json.get("mac").toString());
            //返回空，无此设备
            if (operateDeviceWhiteListVO == null) {
                return this.encryptResult(new MessageVO(AppErrorCodeEnum.DEVICE_IS_NOT_WHITE_LIST.getErrorCode()), encryptionAbility);
            }
            //status = 2 mac地址被禁用
            if (operateDeviceWhiteListVO.getStatus() == 2) {
                return this.encryptResult(new MessageVO(AppErrorCodeEnum.DEVICE_IS_FORBIDDEN_IN_WHITE_LIST.getErrorCode()), encryptionAbility);
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("appKey", operateDeviceWhiteListVO.getApiKey());
            resultMap.put("appSecret", operateDeviceWhiteListVO.getApiSecret());
            return this.encryptResult(new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap), encryptionAbility);
        } catch (Exception e) {
            throw new DataAccessException("【云设备】设备地址验证失败", e);
        }
    }

    /**
     * <desc>
     * 加密messageVO
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2020/06/08
     */
    public Map<String, Object> encryptResult(MessageVO messageVO, Integer encryptionAbility) throws Exception {
        String encryptResult = DesEncryptUtil.aesEncrypt(JsonUtil.toJSON(messageVO), cloudElevatorAeskey, cloudElevatorMd5key);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("encryptionAbility", encryptionAbility); //加密方案需要参与响应结果加密
        resultMap.put("encrypScript", encryptResult);
        return resultMap;
    }

    /**
     * <desc>
     * 生成人脸指令
     * </desc>
     *
     * @param deviceUnique 人脸识别仪编号
     * @param userId       用户编号
     * @return
     * @author Qiang.S
     * @createDate 2019/12/24
     */
    @RequestMapping(path = "/device/createUserInstruct", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object createUserInstruct(String deviceUnique, String userId, String deviceType) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            deviceType = request.getAttribute("deviceType") != null && request.getAttribute("deviceUnique").toString().equals("21") ?
                    ((Integer) StringHandlerUtil.strToIntDef(request.getAttribute("deviceType").toString(), 99, 16)).toString() : request.getAttribute("deviceType").toString();
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            userId = request.getAttribute("userId") == null ? null : request.getAttribute("userId").toString();
            if (StringUtils.isBlank(deviceUnique) || StringUtils.isBlank(userId)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isNotBlank(deviceType) && deviceType.equals(PropertyEquipTypeEnum.CLOUD_UNIBODY_FACE_DEVICE.getType().toString())) {
                iCloudEntranceServiceClient.createUserInstruct(deviceUnique, userId);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云设备_createUserInstruct】生成人脸指令失败", e);
        }
    }

    @Value("${" + PlatformConstants.ALIBABA_OSS_ENDPOINT + "}")
    public String ALIBABA_OSS_ENDPOINT;
    @Value("${" + PlatformConstants.ALIBABA_OSS_ACCESSID + "}")
    public String ALIBABA_OSS_ACCESSID;
    @Value("${" + PlatformConstants.ALIBABA_OSS_ACCESSKEY + "}")
    public String ALIBABA_OSS_ACCESSKEY;
    @Value("${" + PlatformConstants.ALIBABA_OSS_BUCKET + "}")
    public String ALIBABA_OSS_BUCKET;
    @Value("${" + PlatformConstants.ALIBABA_OSS_DIR + "}")
    public String ALIBABA_OSS_DIR;
    @Value("${" + PlatformConstants.ALIBABA_OSS_MEDIA_DIR + "}")
    public String ALIBABA_OSS_MEDIA_DIR;
    @Value("${" + PlatformConstants.ALIBABA_OSS_CALLBACKURL + "}")
    public String ALIBABA_OSS_CALLBACKURL;
//    @Value("${" + PlatformConstants.ALIBABA_OSS_MEDIA_CALLBACKURL + "}")
//    public String ALIBABA_OSS_MEDIA_CALLBACKURL;

    /**
     * <desc>
     * 设备日志文件上传
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/12 18:46
     */
    @RequestMapping("/device/uploadLogFiles")
    public Object uploadLogFiles(MultipartFile[] files, String sn, String deviceType, String deviceUnique, @RequestParam(value = "doorNum", required = false) String doorNum) {
        if(null !=  files && files.length <= 0) {
            return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
        }
        LOG.info("sn:" + sn + "deviceType:" + deviceType);
        OSS ossClient = null;
        try {
            for (MultipartFile file : files) {
                LOG.info("文件数量" + files.length + "");
                //保存设备日志文件信息
                DeviceRunLogPO deviceRunLogPO = new DeviceRunLogPO();
                Map<Object, Object> receiveStatus = new HashMap<>();
                deviceRunLogPO.setFileName(file.getOriginalFilename());
                if("33".equals(deviceType)) {
                    deviceRunLogPO.setDeviceUnique(StringHandlerUtil.getElevatorDeviceUniqueBySn(sn));
                }
                if("128".equals(deviceType)) {
                    deviceRunLogPO.setDeviceUnique(StringHandlerUtil.getControllerDeviceUniqueBySn(sn));
                }
//                if("17".equals(deviceType) || "22".equals(deviceType) || "23".equals(deviceType) || "24".equals(deviceType)) {
//                    if("17".equals(deviceType) || "22".equals(deviceType) || "23".equals(deviceType)){
//                        StringBuffer sb = new StringBuffer(doorNum);
//                        for (int i = sb.length(); i < 4; i++) {
//                            sb.insert(0, "0");
//                        }
//                        sn = sn.substring(0, sn.length()-4 ) + sb.toString();
//                    }
//
//                    deviceRunLogPO.setDeviceUnique(StringHandlerUtil.getEntranceDeviceUniqueBySn(sn));
//                }

                if("17".equals(deviceType) || "22".equals(deviceType) || "23".equals(deviceType) || "24".equals(deviceType) || "18".equals(deviceType)) {
                    if(StringUtils.isNotBlank(doorNum)) {
                        StringBuffer sb = new StringBuffer(doorNum);
                        for (int i = sb.length(); i < 4; i++) {
                            sb.insert(0, "0");
                        }
                        sn = sn.substring(0, sn.length()-4 ) + sb.toString();
                    }
                    deviceRunLogPO.setDeviceUnique(StringHandlerUtil.getEntranceDeviceUniqueBySn(sn));
                    if("17".equals(deviceType)) {
                        receiveStatus.put("deviceType", 2);
                        deviceRunLogPO.setDeviceType(2);
                    }
                    if("22".equals(deviceType)) {
                        receiveStatus.put("deviceType", 4);
                        deviceRunLogPO.setDeviceType(4);
                    }
                    if("24".equals(deviceType)) {
                        receiveStatus.put("deviceType", 6);
                        deviceRunLogPO.setDeviceType(6);
                    }
                    if("18".equals(deviceType)) {
                        receiveStatus.put("deviceType", 2);
                        deviceRunLogPO.setDeviceType(2);
                    }
                }

                if(StringUtils.isNotBlank(deviceUnique)) {
                    deviceRunLogPO.setDeviceUnique(deviceUnique);
                }


//                receiveStatus.put("phase", 2);
//                receiveStatus.put("time", System.currentTimeMillis());
//                receiveStatus.put("size", 0);

                receiveStatus.put("phase", 2);
                receiveStatus.put("createTime", new Date());
                receiveStatus.put("fileName", file.getOriginalFilename());
                receiveStatus.put("sn", sn);

                receiveStatus.put("fileSize", file.getSize());
                receiveStatus.put("uploadStatus", 99);
                redisService.set(deviceRunLogPO.getDeviceUnique(), 180L, JSON.toJSONString(receiveStatus));

                deviceRunLogPO.setDeviceType(StringHandlerUtil.getDeviceTypeByDeviceUnique(deviceRunLogPO.getDeviceUnique()));
                deviceRunLogPO.setSn(sn);
                deviceRunLogPO.setUploadStatus(0);
                deviceRunLogPO.setStatus(1);

                deviceRunLogPO.setRunLogId(idWorker.nextId() + "");
                deviceRunLogPO.setCreateTime(new Date());
                deviceRunLogPO.setFileSize(file.getSize());
                iCloudDeviceBaseService.saveDeviceRunLog(deviceRunLogPO);
                // Endpoint以杭州为例，其它Region请按实际情况填写。
                String endpoint = ALIBABA_OSS_ENDPOINT;
                // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
                String accessKeyId = ALIBABA_OSS_ACCESSID;
                String accessKeySecret = ALIBABA_OSS_ACCESSKEY;

                // 创建OSSClient实例。
                ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                Log.info("【设备日志文件上传】文件名称：" +file.getOriginalFilename());
                // 上传Byte数组。
                PutObjectRequest putObjectRequest = new PutObjectRequest(ALIBABA_OSS_BUCKET, file.getOriginalFilename(),new ByteArrayInputStream(file.getBytes()));
//                PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

                // 上传回调参数
                Callback callback = new Callback();
                callback.setCallbackUrl(ALIBABA_OSS_CALLBACKURL);
                //（可选）设置回调请求消息头中Host的值，即您的服务器配置Host的值。
                // callback.setCallbackHost("yourCallbackHost");
                // 设置发起回调时请求body的值。
                callback.setCallbackBody("{\\\"sn\\\":${x:sn},\\\"deviceType\\\":${x:deviceType},\\\"deviceUnique\\\":${x:deviceUnique},\\\"fileName\\\":${x:fileName}}");

                // 设置发起回调请求的Content-Type。
                callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
                callback.addCallbackVar("x:sn", sn);
                callback.addCallbackVar("x:deviceType", deviceType);
                callback.addCallbackVar("x:deviceUnique", deviceRunLogPO.getDeviceUnique());
                callback.addCallbackVar("x:fileName", file.getOriginalFilename());
                putObjectRequest.setCallback(callback);
                PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
                // 读取上传回调返回的消息内容。
                byte[] buffer = new byte[1024];
                int read = putObjectResult.getResponse().getContent().read(buffer);
                LOG.info("上传回调返回的消息内容>>>>>>>>>>>>>>>>>>>>>>>>>>==========================================================" + read);
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                putObjectResult.getResponse().getContent().close();
                // 关闭OSSClient。
//                ossClient.shutdown();
            }
        } catch (Exception e) {
            Log.error("【设备日志文件上传】错误：" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }

        }
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
    }


    @RequestMapping(value = "/OSSCallBack", method = RequestMethod.POST)
    @ResponseBody
    public Object OSSCallBack(@RequestBody DeviceRunLogPO deviceRunLogPO) {
        LOG.info("有请求进来参数为：" + JSON.toJSONString(deviceRunLogPO));
        deviceRunLogPO.setUploadStatus(100);
        Integer row = iCloudDeviceBaseService.updateDeviceRunLog(deviceRunLogPO);
        HashMap<String, Object> map = new HashMap<>();
        map.put("phase", 3);
        map.put("createTime", new Date());
        map.put("fileName", deviceRunLogPO.getFileName());
        map.put("sn", deviceRunLogPO.getSn());
        map.put("deviceType", deviceRunLogPO.getDeviceType());
        map.put("uploadStatus", 100);
        redisService.set(deviceRunLogPO.getDeviceUnique(), 180L, JSON.toJSONString(map));
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
    }


    public static void main(String[] args) {
        String s = "0000012200000025";
        StringBuffer sb = new StringBuffer(Integer.valueOf(StringHandlerUtil.getDeviceIdBySn(s)) + "");
        for (int i = sb.length(); i < 4; i++){


        }
    }

    /**
     * <desc>
     *      运维和SDK服务保持心跳调用
     * <desc/>
     *
     * @param request
     * @return
     * @author Juguang.S
     * @createDate 2020/12/30
     */
    @UnAuthAccessRequired
    @UnLogIntercept
    @RequestMapping(value = "/nginx/heartbeat")
    public Object service(HttpServletRequest request) {
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
    }
}
